#include "HttpServer.h"
#include "TcpConnection.h"
#include <iostream>
#include <mutex>
#include <unordered_map>
#include <ctime>

using std::cout;
using std::endl;
using std::cerr;

HttpServer::HttpServer(const std::string &ip, unsigned short port, 
                       int subReactorNum, int threadNum, int queueSize)
: _tcpServer(ip, port, subReactorNum, threadNum, queueSize)
{
    // 设置TCP服务器的回调函数
    _tcpServer.setAllCallback(
        std::bind(&HttpServer::onNewConnection, this, std::placeholders::_1),
        std::bind(&HttpServer::onMessage, this, std::placeholders::_1),
        std::bind(&HttpServer::onClose, this, std::placeholders::_1)
    );
    
    // 添加默认CORS中间件
    use([](const HttpRequest& request, HttpResponse& response) -> bool {
        if (request.getMethod() == HttpMethod::OPTIONS) {
            response.enableCORS();
            response.setStatusCode(HttpStatusCode::NO_CONTENT);
            return false; // 拦截OPTIONS请求
        }
        response.enableCORS();
        return true; // 继续处理
    });
}

HttpServer::~HttpServer()
{
}

void HttpServer::start()
{
    cout << "HTTP服务器启动中..." << endl;
    cout << "多Reactor架构 + 线程池 + HTTP协议支持" << endl;
    _tcpServer.start();
}

void HttpServer::stop()
{
    _tcpServer.stop();
}

void HttpServer::get(const std::string& path, HttpHandler handler)
{
    _router.get(path, handler);
}

void HttpServer::post(const std::string& path, HttpHandler handler)
{
    _router.post(path, handler);
}

void HttpServer::put(const std::string& path, HttpHandler handler)
{
    _router.put(path, handler);
}

void HttpServer::del(const std::string& path, HttpHandler handler)
{
    _router.del(path, handler);
}

void HttpServer::options(const std::string& path, HttpHandler handler)
{
    _router.options(path, handler);
}

void HttpServer::route(HttpMethod method, const std::string& path, HttpHandler handler)
{
    _router.route(method, path, handler);
}

void HttpServer::serveStatic(const std::string& urlPrefix, const std::string& localPath)
{
    _router.serveStatic(urlPrefix, localPath);
}

void HttpServer::use(Middleware middleware)
{
    _router.use(middleware);
}

void HttpServer::onNewConnection(const TcpServer::TcpConnectionPtr &conn)
{
    cout << "[HTTP] 新连接建立: " << conn->toString() << endl;
    
    // 初始化连接缓冲区
    std::lock_guard<std::mutex> lock(_buffersMutex);
    _connectionBuffers[conn->fd()] = "";
}

void HttpServer::onMessage(const TcpServer::TcpConnectionPtr &conn)
{
    string data = conn->receive();
    if (data.empty()) {
        return;
    }
    
    int connFd = conn->fd();
    
    // 将数据添加到连接缓冲区
    {
        std::lock_guard<std::mutex> lock(_buffersMutex);
        _connectionBuffers[connFd] += data;
    }
    
    // 检查是否有完整的HTTP请求
    string buffer;
    {
        std::lock_guard<std::mutex> lock(_buffersMutex);
        buffer = _connectionBuffers[connFd];
    }
    
    // 查找HTTP请求结束标记
    size_t requestEndPos = buffer.find("\r\n\r\n");
    if (requestEndPos != string::npos) {
        // 检查是否需要等待请求体
        string headerPart = buffer.substr(0, requestEndPos);
        
        // 简单解析Content-Length
        size_t contentLengthPos = headerPart.find("Content-Length:");
        if (contentLengthPos == string::npos) {
            contentLengthPos = headerPart.find("content-length:");
        }
        
        size_t contentLength = 0;
        if (contentLengthPos != string::npos) {
            size_t valueStart = headerPart.find(':', contentLengthPos) + 1;
            size_t valueEnd = headerPart.find('\r', valueStart);
            if (valueEnd == string::npos) valueEnd = headerPart.find('\n', valueStart);
            
            string lengthStr = headerPart.substr(valueStart, valueEnd - valueStart);
            // 去除空格
            lengthStr.erase(0, lengthStr.find_first_not_of(" \t"));
            lengthStr.erase(lengthStr.find_last_not_of(" \t") + 1);
            
            try {
                contentLength = std::stoul(lengthStr);
            } catch (...) {
                contentLength = 0;
            }
        }
        
        size_t totalExpected = requestEndPos + 4 + contentLength;
        if (buffer.length() >= totalExpected) {
            // 有完整的请求
            string completeRequest = buffer.substr(0, totalExpected);
            
            // 处理HTTP请求
            handleHttpRequest(conn, completeRequest);
            
            // 从缓冲区移除已处理的请求
            {
                std::lock_guard<std::mutex> lock(_buffersMutex);
                _connectionBuffers[connFd] = buffer.substr(totalExpected);
            }
        }
    }
}

void HttpServer::onClose(const TcpServer::TcpConnectionPtr &conn)
{
    cout << "[HTTP] 连接关闭: " << conn->toString() << endl;
    
    // 清理连接缓冲区
    std::lock_guard<std::mutex> lock(_buffersMutex);
    _connectionBuffers.erase(conn->fd());
}

void HttpServer::handleHttpRequest(const TcpServer::TcpConnectionPtr &conn, const std::string& requestData)
{
    HttpRequest request;
    HttpResponse response;
    
    // 解析HTTP请求
    if (!request.parseRequest(requestData)) {
        cout << "[HTTP] 请求解析失败" << endl;
        response.setStatusCode(HttpStatusCode::BAD_REQUEST);
        response.setPlainTextContent("Bad Request");
    } else {
        cout << "[HTTP] " << request.getMethodString() 
             << " " << request.getPath() << endl;
        
        // 使用路由器处理请求
        _router.handleRequest(request, response);
    }
    
    // 发送响应
    string responseData = response.buildResponse();
    conn->send(responseData);
}